import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Statistic, Progress, DatePicker, Select, Spin } from 'antd';
import { 
  ArrowUpOutlined, 
  CheckCircleOutlined,
  WarningOutlined
} from '@ant-design/icons';
import LineChart from '../Charts/LineChart';
import PieChart from '../Charts/PieChart';
import './Dashboard.css';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface DashboardProps {
  deviceId?: string;
  onlyShowSummary?: boolean;
}

interface DataPoint {
  time: string;
  value: number;
}

interface DataItem {
  name: string;
  value: number;
  color: string;
}

const Dashboard: React.FC<DashboardProps> = ({ 
  deviceId,
  onlyShowSummary = false
}) => {
  const [loading, setLoading] = useState<boolean>(true);
  const [dateRange, setDateRange] = useState<[Date, Date] | null>(null);
  const [interval, setInterval] = useState<string>('hour');
  const [temperatureData, setTemperatureData] = useState<DataPoint[]>([]);
  const [humidityData, setHumidityData] = useState<DataPoint[]>([]);
  const [batteryData, setBatteryData] = useState<DataPoint[]>([]);
  const [statusData, setStatusData] = useState<DataItem[]>([]);
  
  // 生成模拟数据
  useEffect(() => {
    setLoading(true);
    
    setTimeout(() => {
      // 模拟温度数据
      const tempData: DataPoint[] = [];
      const humData: DataPoint[] = [];
      const batData: DataPoint[] = [];
      
      // 当前时间
      const now = new Date();
      
      // 生成过去24小时的数据点
      for (let i = 24; i >= 0; i--) {
        const time = new Date(now.getTime() - i * 60 * 60 * 1000);
        const timeStr = `${time.getHours().toString().padStart(2, '0')}:00`;
        
        // 随机数据波动
        tempData.push({
          time: timeStr,
          value: 25 + Math.random() * 5 - 2.5 // 温度在22.5-27.5之间波动
        });
        
        humData.push({
          time: timeStr,
          value: 45 + Math.random() * 10 - 5 // 湿度在40-50之间波动
        });
        
        batData.push({
          time: timeStr,
          value: Math.max(0, 100 - i * 0.8 - Math.random() * 2) // 电池电量随时间下降
        });
      }
      
      // 状态分布
      const statData: DataItem[] = [
        { name: '正常', value: 42, color: '#52c41a' },
        { name: '警告', value: 8, color: '#faad14' },
        { name: '错误', value: 3, color: '#f5222d' },
        { name: '未知', value: 2, color: '#d9d9d9' }
      ];
      
      setTemperatureData(tempData);
      setHumidityData(humData);
      setBatteryData(batData);
      setStatusData(statData);
      setLoading(false);
    }, 1500);
  }, [deviceId, dateRange, interval]);
  
  const handleDateRangeChange = (dates: any) => {
    setDateRange(dates);
  };
  
  const handleIntervalChange = (value: string) => {
    setInterval(value);
  };
  
  return (
    <div className="dashboard-container">
      {!onlyShowSummary && (
        <div className="dashboard-header">
          <div className="filter-group">
            <RangePicker onChange={handleDateRangeChange} />
            <Select 
              defaultValue="hour" 
              style={{ width: 120, marginLeft: 8 }} 
              onChange={handleIntervalChange}
            >
              <Option value="minute">分钟</Option>
              <Option value="hour">小时</Option>
              <Option value="day">天</Option>
              <Option value="week">周</Option>
            </Select>
          </div>
        </div>
      )}
      
      <Spin spinning={loading}>
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={8} lg={6}>
            <Card>
              <Statistic
                title="温度"
                value={temperatureData.length > 0 ? temperatureData[temperatureData.length - 1].value : 0}
                precision={1}
                valueStyle={{ color: '#1890ff' }}
                prefix={<ArrowUpOutlined />}
                suffix="°C"
              />
              <div className="stat-footer">
                <span className="stat-change positive">+0.5°C</span>
                <span className="stat-period">与昨日相比</span>
              </div>
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={8} lg={6}>
            <Card>
              <Statistic
                title="湿度"
                value={humidityData.length > 0 ? humidityData[humidityData.length - 1].value : 0}
                precision={1}
                valueStyle={{ color: '#52c41a' }}
                suffix="%"
              />
              <div className="stat-footer">
                <span className="stat-change negative">-2.3%</span>
                <span className="stat-period">与昨日相比</span>
              </div>
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={8} lg={6}>
            <Card>
              <Statistic
                title="电池电量"
                value={batteryData.length > 0 ? batteryData[batteryData.length - 1].value : 0}
                precision={0}
                valueStyle={{ color: batteryData.length > 0 && batteryData[batteryData.length - 1].value < 20 ? '#f5222d' : '#52c41a' }}
                suffix="%"
              />
              <Progress 
                percent={batteryData.length > 0 ? batteryData[batteryData.length - 1].value : 0} 
                showInfo={false}
                strokeColor={batteryData.length > 0 && batteryData[batteryData.length - 1].value < 20 ? '#f5222d' : undefined}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={8} lg={6}>
            <Card>
              <Statistic
                title="设备状态"
                value="正常"
                valueStyle={{ color: '#52c41a' }}
                prefix={<CheckCircleOutlined />}
              />
              <div className="status-indicators">
                <span className="status-item">
                  <CheckCircleOutlined style={{ color: '#52c41a' }} /> 传感器
                </span>
                <span className="status-item">
                  <CheckCircleOutlined style={{ color: '#52c41a' }} /> 连接
                </span>
                <span className="status-item">
                  <WarningOutlined style={{ color: '#faad14' }} /> 电量
                </span>
              </div>
            </Card>
          </Col>
        </Row>
        
        {!onlyShowSummary && (
          <>
            <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
              <Col xs={24} md={12}>
                <LineChart 
                  title="温度变化趋势" 
                  data={temperatureData}
                  yAxisLabel="温度 (°C)"
                  xAxisLabel="时间"
                  color="#1890ff"
                />
              </Col>
              <Col xs={24} md={12}>
                <LineChart 
                  title="湿度变化趋势" 
                  data={humidityData}
                  yAxisLabel="湿度 (%)"
                  xAxisLabel="时间"
                  color="#52c41a"
                />
              </Col>
            </Row>
            
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <LineChart 
                  title="电池电量变化" 
                  data={batteryData}
                  yAxisLabel="电量 (%)"
                  xAxisLabel="时间"
                  color="#faad14"
                />
              </Col>
              <Col xs={24} md={12}>
                <PieChart
                  title="设备状态分布"
                  data={statusData}
                />
              </Col>
            </Row>
          </>
        )}
      </Spin>
    </div>
  );
};

export default Dashboard; 